package com.yitong.Estshopping.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.yitong.Estshopping.entity.Order;
import com.yitong.Estshopping.entity.Orderlog;
import com.yitong.Estshopping.entity.PayEntity;
import com.yitong.Estshopping.entity.User;
import com.yitong.Estshopping.entity.Walletlog;
import com.yitong.Estshopping.service.OrderLogService;
import com.yitong.Estshopping.service.OrderService;
import com.yitong.Estshopping.service.PayInfoService;
import com.yitong.confg.AlipayConfig;
import com.yitong.framework.Orderlogtext;
import com.yitong.framework.utils.Dingdan;
import com.yitong.framework.utils.UpdateClass;

@Controller
public class PayController {
	@Autowired
	private PayInfoService payInfoService;
	/**
	 * 支付接口
	 * @param request
	 * @param response
	 * @param out_trade_no 订单号
	 * @param uname 用户名
	 * @param subject 内容
	 * @param total_amount 金额
	 * @param body 详情
	 * @param payEntity postjosn解析
	 * @throws AlipayApiException
	 * @throws IOException
	 */
	@RequestMapping(value="/playzhifu")
	public void playzhifu(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required=false) String out_trade_no,
			@RequestParam(required=false) String uid,
			@RequestParam(required=false) String uname,
			@RequestParam(required=false) String subject,
			@RequestParam(required=false) String total_amount,
			@RequestParam(required=false) String body,
			@RequestBody(required=false) PayEntity payEntity
			) throws AlipayApiException, IOException {
		ModelAndView view = null;
		System.out.println(out_trade_no);
		boolean empty = ObjectUtils.isEmpty(payEntity);
		System.out.println(empty);
		if(empty) {
			boolean empty2 = ObjectUtils.isEmpty(out_trade_no);
			if (empty2) {
				response.sendRedirect("/zanzhu");
				//view = new ModelAndView("redirect:/zanzhu");
				return;
			}
		}
		PayEntity payEntity2 = new PayEntity();
		payEntity2.setOut_trade_no(out_trade_no);
		payEntity2.setUid(uid);
		payEntity2.setUname(uname);
		payEntity2.setSubject(subject);
		payEntity2.setTotal_amount(total_amount);
		payEntity2.setBody(body);
		if(payEntity2.getOut_trade_no()!=null
				&&payEntity2.getSubject()!=null
				&&payEntity2.getTotal_amount()!=null) {
			payEntity=payEntity2;
		}
		//System.out.println(payEntity.toString());
		
		// 根据订单号查找相应的记录:根据结果跳转到不同的页面
		boolean isTrue = false;
		//if(payEntity.getOut_trade_no()==null)view = new ModelAndView("/zanzhu");
		if(payEntity.getOut_trade_no()==null
			&&payEntity.getSubject()==null
			&&payEntity.getTotal_amount()==null
		) {
			response.sendRedirect("/zanzhu");
			return;
		}
		
		
		/**
		 * 支付业务
		 */
		String form="";
		AlipayClient client = new DefaultAlipayClient(
				AlipayConfig.URL, 
				AlipayConfig.APPID, 
				AlipayConfig.RSA_PRIVATE_KEY, 
				AlipayConfig.FORMAT, 
				AlipayConfig.CHARSET, 
				AlipayConfig.ALIPAY_PUBLIC_KEY,
				AlipayConfig.SIGNTYPE);
	   
	    Device device = DeviceUtils.getCurrentDevice(request);
	    if (device.isMobile()|| device.isTablet()) {
	    	AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
	    	 // 设置异步通知地址
		    alipay_request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
		    // 设置同步地址
		    alipay_request.setReturnUrl(AlipayConfig.RETURN_URL); 
	    	System.out.println("1");
	    	//手机端 平板端
	    	// 封装请求支付信息
	        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
	        model.setOutTradeNo(payEntity.getOut_trade_no());
	        model.setSubject(payEntity.getSubject());
	        model.setTotalAmount(payEntity.getTotal_amount());
	        model.setBody(payEntity.getBody());
	        model.setTimeoutExpress(payEntity.getTimeout_express());
	        model.setProductCode("QUICK_WAP_PAY");
	        alipay_request.setBizModel(model);
	        payInfoService.save(payEntity);
	        form = client.pageExecute(alipay_request).getBody(); //调用SDK生成表单
	        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
	        response.getWriter().write(form);//直接将完整的表单html输出到页面
	        response.getWriter().flush();
	        response.getWriter().close();
    	    
	    	
	    } else {
	    	AlipayTradePagePayRequest alipay_request = new AlipayTradePagePayRequest();
	    	 // 设置异步通知地址
		    alipay_request.setNotifyUrl(AlipayConfig.NOTIFY_URL);
		    // 设置同步地址
		    alipay_request.setReturnUrl(AlipayConfig.RETURN_URL);
		    //电脑端
	    	System.out.println("电脑端支付");
	    	alipay_request.setBizContent("{\"out_trade_no\":\""+ payEntity.getOut_trade_no() +"\"," 
	    			+ "\"total_amount\":\""+ payEntity.getTotal_amount() +"\"," 
	    			+ "\"subject\":\""+ payEntity.getSubject() +"\"," 
	    			+ "\"body\":\""+ payEntity.getBody() +"\"," 
	    			//+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
	    			+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
	    	payEntity.setProduct_code("2");
	      
	    	payInfoService.save(payEntity);
	        form = client.pageExecute(alipay_request).getBody(); //调用SDK生成表单
	            //view = new ModelAndView("/payHtml","form",form);
	        //map.put("form", form); 
	        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
	        response.getWriter().write(form);//直接将完整的表单html输出到页面
	        response.getWriter().flush();
	        response.getWriter().close();
	        //session.setAttribute("form", form);
	    }
	    /**
		 * 记录支付信息
		 * 
		 */
		
		//return "redirect:/payHtml";
	}
	
	@RequestMapping("/playnotreturn")
	public ModelAndView playnotreturn(HttpServletRequest request, HttpServletResponse response,PayEntity payEntity) {
		boolean isTrue = false;
		ModelAndView view = null;
		System.out.println("playnotreturn"+payEntity);
		// 根据订单号查找相应的记录:根据结果跳转到不同的页面
		if (isTrue) {
			view = new ModelAndView("/正确的跳转地址");
		} else {
			view = new ModelAndView("/没有支付成功的地址");
		}
		return view;
	}
	
	

	@RequestMapping("/playreturn")
	public String returnPay(HttpServletRequest request, HttpServletResponse response, PayEntity payEntity) throws IOException {
		boolean isTrue = false;
		System.out.println("playreturn"+payEntity);
		// 根据订单号查找相应的记录:根据结果跳转到不同的页面
		String out_trade_no = payEntity.getOut_trade_no();
		payInfoService.update(payEntity);
		return "redirect:/payHtml/"+out_trade_no;
		
	}
	/**
	 * 支付完成页面
	 */
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderLogService orderlogservice;
	@RequestMapping("/payHtml/{out_trade_no}")
	public String payHtml(HttpSession session,@PathVariable("out_trade_no") String out_trade_no) {
		User user = (User) session.getAttribute("user");
		PayEntity payentity = payInfoService.getOut_trade_no(out_trade_no);
		session.setAttribute("payentity", payentity);
		/**
		 * 商品返回页
		 */
		Order order = orderService.findOif(out_trade_no);
		if(order!=null) {
			String oif = order.getOif();
			order.setState(2);
			boolean flag = orderService.update(order);
			
			//日志记录
			Orderlog textlog = Orderlogtext.textlog(user, oif, order,2);
			orderlogservice.seve(textlog );
			session.setAttribute("iShref", true);
		}
		return "payHtml";
	}
	/**
	 * 退款协议
	 * @param session
	 * @param out_trade_no
	 * @return
	 * @throws AlipayApiException 
	 * @throws IOException 
	 */
	@RequestMapping("/alipayRequest/{out_trade_no}")
	public void alipayRequestHtml(HttpServletRequest request, HttpServletResponse response,HttpSession session,@PathVariable("out_trade_no") String out_trade_no) throws AlipayApiException, IOException {
		User user = (User) session.getAttribute("user");
		String result = null;
		PayEntity payentity = payInfoService.getOut_trade_no(out_trade_no);
		if(payentity!=null) {
			//获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
			
			//设置请求参数
			AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
			String total_amount = payentity.getTotal_amount();
			float f1 = Float.parseFloat(total_amount);
			double d=0;
			float f = 0;
			if(f1>=0.1f) {
				d = f1*0.08;
				f=(float) (f1-d);
			}
			float r = f1-f;
			BigDecimal b = new BigDecimal(f);
			Float total = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
			String body = "退款"+payentity.getSubject()+"订单说明"+payentity.getBody()+"退款手续费:"+r+"元";
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
					+ "\"trade_no\":\""+ payentity.getOut_trade_no() +"\"," 
					+ "\"refund_amount\":\""+ total +"\"," 
					+ "\"refund_reason\":\""+ body +"\"," 
					+ "\"out_request_no\":\""+ "TK"+Dingdan.diof() +"\"}");
			
			//请求
			result = alipayClient.execute(alipayRequest).getBody();
		}
		response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        response.getWriter().write(result);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
	}
}
